<?php

namespace App\Console\Commands;

use App\Models\Book;
use App\Models\Word;
use App\Models\WordExam;
use App\Models\WordPhrase;
use App\Models\WordSentence;
use App\Models\WordTrans;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class ImportDictDataCommand extends Command
{
    protected $signature = 'app:import-dict-data-command';

    protected $description = 'import dict data';

    public function handle()
    {
        $this->importBook();
        $this->importWord();
    }

    public function importBook()
    {
        $bookList = storage_path('app/public/dict/bookLists.txt');
        $bookStr = file_get_contents($bookList);
        $bookArr = json_decode($bookStr, true);
        $books = $bookArr['data']['normalBooksInfo'];
        $total = count($books);

        $this->info('开始导入Book...');
        $bar = $this->output->createProgressBar($total);
        $bar->start();

        DB::statement('truncate books');
        foreach ($books as $key => $book) {
            $data = [
                'key' => $book['id'],
                'name' => $book['title'],
                'full_name' => $book['title'],
                'introduce' => $book['introduce'],
                'word_num' => $book['wordNum'],
                'origin' => $book['bookOrigin']['originName'],
                'organization' => $book['tags'][1]['tagName'] ?? '',
                'publisher' => $book['tags'][0]['tagName'] ?? '',
                'cover' => $book['cover'],
                'sort' => $key,
                'version' => $book['version'],
            ];

            Book::query()->create($data);
            $bar->advance();
        }

        $bar->finish();
        $this->newLine();
        $this->info('导入Book完成, 共'.$total);

        Book::query()->where('key', 'like', '%XiaoXue%')->update(['category_id' => 1, 'sort' => 600]);
        Book::query()->where('key', 'like', '%ChuZhong%')->update(['category_id' => 2, 'sort' => 500]);
        Book::query()->where('key', 'like', '%GaoZhong%')->update(['category_id' => 3, 'sort' => 400]);
        Book::query()->where('key', 'like', '%CET4%')->update(['category_id' => 4, 'sort' => 300]);
        Book::query()->where('key', 'like', '%CET6%')->update(['category_id' => 5, 'sort' => 200]);
        Book::query()->where('key', 'like', '%CET8%')->update(['category_id' => 6, 'sort' => 100]);
        Book::query()->where('category_id', 0)->update(['is_enable' => 0]);

        $this->newLine(2);
    }

    public function importWord()
    {
        ini_set('memory_limit', '300M');
        $books = Book::query()->where('is_enable', 1)->get();
        $total = count($books);
        $i = 0;

        DB::statement('TRUNCATE words');
        DB::statement('TRUNCATE word_trans');
        DB::statement('TRUNCATE word_exams');
        DB::statement('TRUNCATE word_sentences');
        DB::statement('TRUNCATE word_phrases');

        $this->info('开始导入Word...');
        $bar = $this->output->createProgressBar($total);
        $bar->start();
        foreach ($books as $book) {
            $filename = storage_path('app/public/dict/book_json/') . $book['key'] . '.json';
            $content = file($filename, FILE_IGNORE_NEW_LINES);
            $words = [];

            foreach ($content as $line) {
                $arr = json_decode($line, true);
                $wordContent = $arr['content']['word']['content'];
                $wordKey = $arr['content']['word']['wordId'];

                // word
                $words[] = [
                    'book_id' => $book['id'],
                    'book_key' => $book['key'],
                    'word_key' => $wordKey,
                    'word_rank' => $arr['wordRank'],
                    'word' => $arr['headWord'],
                    'phonetic_us' => $wordContent['usphone'] ?? '',
                    'phonetic_uk' => $wordContent['ukphone'] ?? '',
                    'speech_uk' => $wordContent['ukspeech'] ?? '',
                    'speech_us' => $wordContent['usspeech'] ?? '',
                    'cover' => '',
                    'created_at' => date('Y-m-d H:i:s'),
                ];
                if (count($words) >= 2000) {
                    Word::query()->insert($words);
                    $words = [];
                }

                $i++;
            }

            if (count($words)) {
                Word::query()->insert($words);
            }

            unset($content);
            $bar->advance();
        }
        $bar->finish();
        $this->newLine();
        $this->info('导入Word完成，共'.$i);

        $this->newLine(2);
        $this->info('开始导入Word的关联表...');
        $wordMap = Word::query()->pluck('id', 'word_key');
        $bar2 = $this->output->createProgressBar($total);
        $bar2->start();
        foreach ($books as $book) {
            $filename = storage_path('app/public/dict/book_json/') . $book['key'] . '.json';
            $content = file($filename, FILE_IGNORE_NEW_LINES);
            $trans = $exams = $sentences = $phrases = [];

            foreach ($content as $line) {
                $arr = json_decode($line, true);
                $wordContent = $arr['content']['word']['content'];
                $wordKey = $arr['content']['word']['wordId'];

                // word trans
                $transArr = $wordContent['trans'];
                if (count($transArr)) {
                    foreach ($transArr as $arr1) {
                        $trans[] = [
                            'word_id' => $wordMap[$wordKey] ?? 0,
                            'word_key' => $wordKey,
                            'pos' => $arr1['pos']??'',
                            'tran_cn' => $arr1['tranCn'],
                            'tran_en' => $arr1['tranOther'] ?? '',
                            'created_at' => date('Y-m-d H:i:s'),
                        ];
                    }
                }
                if (count($trans) >= 2000) {
                    WordTrans::query()->insert($trans);
                    $trans = [];
                }

                // word exams
                $examArr = $wordContent['exam'] ?? [];
                if (count($examArr)) {
                    $exams = [];
                    foreach ($examArr as $arr2) {
                        $exams[] = [
                            'word_id' => $wordMap[$wordKey] ?? 0,
                            'word_key' => $wordKey,
                            'question' => $arr2['question'],
                            'choices' => json_encode($arr2['choices'], JSON_UNESCAPED_UNICODE),
                            'answer' => json_encode($arr2['answer'], JSON_UNESCAPED_UNICODE),
                            'type' => $arr2['examType'],
                            'created_at' => date('Y-m-d H:i:s'),
                        ];
                    }
                }
                if (count($exams) >= 2000) {
                    WordExam::query()->insert($exams);
                    $exams = [];
                }

                // word sentences
                $sentenceArr = $wordContent['sentence']['sentences'] ?? [];
                if (count($sentenceArr)) {
                    foreach ($sentenceArr as $arr3) {
                        $sentences[] = [
                            'word_id' => $wordMap[$wordKey] ?? 0,
                            'word_key' => $wordKey,
                            'content' => $arr3['sContent'],
                            'tran_cn' => $arr3['sCn'],
                            'created_at' => date('Y-m-d H:i:s'),
                        ];
                    }
                }
                if (count($sentences) == 2000) {
                    WordSentence::query()->insert($sentences);
                    $sentences = [];
                }

                // word phrase
                $phraseArr = $wordContent['phrase']['phrases'] ?? [];
                if (count($phraseArr)) {
                    foreach ($phraseArr as $arr4) {
                        $phrases[] = [
                            'word_id' => $wordMap[$wordKey] ?? 0,
                            'word_key' => $wordKey,
                            'content' => $arr4['pContent'],
                            'tran_cn' => $arr4['pCn'],
                            'created_at' => date('Y-m-d H:i:s'),
                        ];
                    }
                }
                if (count($phrases) >= 2000) {
                    WordPhrase::query()->insert($phrases);
                    $phrases = [];
                }

                $i++;
            }

            if (count($trans)) {
                WordTrans::query()->insert($trans);
            }
            if (count($exams)) {
                WordExam::query()->insert($exams);
            }
            if (count($sentences)) {
                WordSentence::query()->insert($sentences);
            }
            if (count($phrases)) {
                WordPhrase::query()->insert($phrases);
            }

            unset($content);
            $bar2->advance();
        }
        $bar2->finish();

        $this->newLine();
        $this->info('导入Word的关联表完成');
    }

}
